import { toRaw, watch } from "vue";
import { reactive } from "vue";

export default function usePage(params: UsePageParams): PageInfo {
	let request = () => {
		if (params.getData) {
			//目的是获取的对象不触发watch更新
			let temp = toRaw(page);
			temp.totalPages = params.getData(page.currPage, page.rowNumber);
		}
	};

	let init = () => {
		page.currPage = params.currPage ? params.currPage : 1;
		page.totalPages = params.totalPages ? params.totalPages : 1;
		page.rowNumber = params.rowNumber ? params.rowNumber : 20;
	};

	let next = () => {
		page.setPage(page.currPage + 1);
	};

	let refresh = () => {
		request();
	};

	let setPage = (currPage: number) => {
		if (currPage <= page.totalPages && currPage != page.currPage && currPage > 0) {
			page.currPage = currPage;
		} else {
			console.warn("设置页面参数错误。不能小于等于0或者大于count.当前值:", currPage, page);
		}
	};

	let setRowNumber = (rowNumber: number) => {
		if (rowNumber > 0) {
			page.totalPages = (page.totalPages * page.rowNumber) / rowNumber;
			page.currPage = 1;
			page.rowNumber = rowNumber;
		}
	};

	const page = reactive<PageInfo>({
		currPage: params.currPage ? params.currPage : 0,
		totalPages: params.totalPages ? params.totalPages : 1,
		rowNumber: params.rowNumber ? params.rowNumber : 20,
		init: init,
		next: next,
		refresh: refresh,
		setPage: setPage,
		setRowNumber: setRowNumber,
	});

	watch(page, () => {
		request();
	});

	return page;
}

interface PageInfo {
	currPage: number;
	totalPages: number;
	rowNumber: number;
	next: () => void;
	init: () => void;
	setPage: (currPage: number) => void;
	setRowNumber: (rowNumber: number) => void;
	refresh: () => void;
}


export interface UsePageParams{
	getData?: (page: number, rowNumber: number) => number,
	totalPages?: number,
	currPage?: number,
	rowNumber?: number
}